import { getUserProfileAPI, postLoginAPI } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, removeToken, setTimeStamp, setToken } from '@/utils/auth'

// 状态
const state = {
  token: getToken(),
  userInfo: {}
}
// 修改状态
const mutations = {
  // 设置token
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 删除缓存
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 修改用户信息
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
// 执行异步
const actions = {
  // 登录
  async login({ commit }, data) {
    const res = await postLoginAPI(data)
    commit('setToken', res.data)
    setTimeStamp() // 存储时间戳
  },
  // 获取用户个人资料
  async getUserProfile({ commit }) {
    const res = await getUserProfileAPI()
    commit('setUserInfo', res.data)
    return res.data
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
    resetRouter()
    commit('permission/setRoutes', [], { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
